package com.dianrui.operation.util;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.support.v4.content.FileProvider;
import android.view.View;
import android.widget.AdapterView;

import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.blankj.utilcode.util.LogUtils;
import com.dianrui.operation.BuildConfig;
import com.dianrui.operation.dialog.FlycoDialog.listener.OnOperItemClickL;
import com.dianrui.operation.dialog.FlycoDialog.widget.ActionSheetDialog;

import java.io.File;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;
import java.util.Stack;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cn.finalteam.galleryfinal.FunctionConfig;
import cn.finalteam.galleryfinal.GalleryFinal;

public class MyUtil {

    private static Stack<Activity> mActivities = new Stack<>();

    private static MyUtil instance = null;

    public static MyUtil getInstance() {
        if (null == instance) {
            synchronized (MyUtil.class) {
                if (null == instance) {
                    instance = new MyUtil();
                }
            }
        }
        return instance;
    }

    public synchronized void clear() {
        int index = size()-1;
        while (index>=0){
            Activity activity = mActivities.pop();
            removeActivity(activity);
            activity.finish();
            index--;
        }
    }

    public synchronized void removeActivity(Activity activity) {
        if (mActivities.contains(activity)) {
            mActivities.remove(activity);
        }
    }


    public int size() {
        return mActivities.size();
    }

    public static void createPhotoChooseDialog(final int requestCode, final int maxSize, final Context context, final FunctionConfig functionConfig, final GalleryFinal.OnHanlderResultCallback listener) {
        String[] stringItems = {"拍照", "相册选取"};
        final ActionSheetDialog dialog = new ActionSheetDialog(context, stringItems, null)
                .isTitleShow(false)
                .itemTextColor(Color.parseColor("#000000"))
                .setmCancelBgColor(Color.parseColor("#FFFFFF"))
                .cancelText(Color.BLACK);
        dialog.title("选择您的方式");
        dialog.titleTextSize_SP(14f).show();
        dialog.setOnOperItemClickL(new OnOperItemClickL() {
            @Override
            public void onOperItemClick(AdapterView<?> parent, View view, int position, long id) {
                switch (position) {
                    case 0:
                        GalleryFinal.openCamera(requestCode, functionConfig, listener);
                        dialog.dismiss();
                        break;
                    case 1:
                        GalleryFinal.openGalleryMuti(requestCode, maxSize, listener);
                        dialog.dismiss();
                        break;

                }
            }
        });

    }

    public static boolean isGpsEnable(Context context) {
        LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        boolean network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        if (gps || network) {
            return true;
        }
        return false;
    }

    public static int getAppVersionCode(Context context) {
        return getAppVersionCode(context, context.getPackageName());
    }

    public static synchronized String getVersionName() {
        return BuildConfig.VERSION_NAME;
    }

    /**
     * 获取App版本码
     *
     * @param context     上下文
     * @param packageName 包名
     * @return App版本码
     */
    public static int getAppVersionCode(Context context, String packageName) {
        if (isSpace(packageName)) return -1;
        try {
            PackageManager pm = context.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(packageName, 0);
            return pi == null ? -1 : pi.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return -1;
        }
    }

    private static boolean isSpace(String s) {
        if (s == null) return true;
        for (int i = 0, len = s.length(); i < len; ++i) {
            if (!Character.isWhitespace(s.charAt(i))) {
                return false;
            }
        }
        return true;
    }

    public static boolean isLetterDigit(String str) {
        String regex = "^[0-9 _-]+$";
        return str.matches(regex);
    }

    public static boolean isUrlDigit(String str) {
        String regex = "^((https|http|ftp|rtsp|mms)?:\\/\\/)[^\\s]+";
        return str.matches(regex);
    }

    public static String formatBy2Scale(Float doubleVal, int scale) {
        if (null == doubleVal) {
            doubleVal = new Float(0);
        }
        StringBuffer sbStr = new StringBuffer("0");
        for (int i = 0; i < scale; i++) {
            sbStr.append("0");
        }
        DecimalFormat myformat = new DecimalFormat(sbStr.toString());
        return myformat.format(doubleVal);
    }


    public static String getUniqueId(Context context){
        String androidID = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
        String id = androidID + Build.SERIAL;
        try {
            return tomd5(id);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return id;
        }
    }

    //直接暴露Android唯一ID有风险，所以将其转化为MD5保险下
    private static String tomd5(String text) throws NoSuchAlgorithmException {
        //获取摘要器 MessageDigest
        MessageDigest messageDigest = MessageDigest.getInstance("MD5");
        //通过摘要器对字符串的二进制字节数组进行hash计算
        byte[] digest = messageDigest.digest(text.getBytes());

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < digest.length; i++) {
            //循环每个字符 将计算结果转化为正整数;
            int digestInt = digest[i] & 0xff;
            //将10进制转化为较短的16进制
            String hexString = Integer.toHexString(digestInt);
            //转化结果如果是个位数会省略0,因此判断并补0
            if (hexString.length() < 2) {
                sb.append(0);
            }
            //将循环结果添加到缓冲区
            sb.append(hexString);
        }
        //返回整个结果
        return sb.toString();
    }

    public static Bitmap getViewBitmap(View addViewContent) {
        addViewContent.setDrawingCacheEnabled(true);
        addViewContent.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        addViewContent.layout(0, 0, addViewContent.getMeasuredWidth(), addViewContent.getMeasuredHeight());
        addViewContent.buildDrawingCache();
        Bitmap cacheBitmap = addViewContent.getDrawingCache();
        return Bitmap.createBitmap(cacheBitmap);
    }

    //设置地图缩放级别
    public static void setMapStatus(MapView mapView, float zoom) {
        mapView.getMap().animateCamera(CameraUpdateFactory.zoomTo(zoom));
    }

    //获取地图缩放级别
    public static float getZoom(MapView mapView) {
        return mapView.getMap().getCameraPosition().zoom;
    }


    /**
     * 正则判断是不是数字
     * @param str
     * @return
     */
    public static boolean isNumeric(String str){
        Pattern pattern = Pattern.compile("[0-9]+");
        Matcher isNum = pattern.matcher(str);
        if( !isNum.matches() ){
            return false;
        }
        return true;
    }

    public static int dip2px(Context context, float dpValue) {
        float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    public static String getAppVersionName(Context context) {
        return getAppVersionName(context, context.getPackageName());
    }

    public static String getAppVersionName(Context context, String packageName) {
        if (isSpace(packageName)) return null;
        try {
            PackageManager pm = context.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(packageName, 0);
            return pi == null ? null : pi.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }


    public static int getScreenWidth(Context context) {
        return context.getResources().getDisplayMetrics().widthPixels;
    }


    public static int getScreenHeight(Context context) {
        return context.getResources().getDisplayMetrics().heightPixels;
    }


    public static int getSDKVersion() {
        return Build.VERSION.SDK_INT;
    }

    /**
     * 安装apk
     *
     * @param context
     * @param apkfile
     */
    public static void installApkNew(Context context, File apkfile) {
        openApk(context, apkfile);
    }

    private static void openApk(Context context, File apkfile) {
        Intent intent = new Intent(Intent.ACTION_VIEW);

        // 由于没有在Activity环境下启动Activity,设置下面的标签
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { //24 : 判读版本是否在7.0以上
            LogUtils.w("Build.VERSION.SDK_INT >= 24 我执行了");

            //在AndroidManifest中的android:authorities值
            //Uri apkUri = FileProvider.getUriForFile(context, "com.leyiquery.dianrui.FileProvider", new File(apkfile.toString()));
            String authority = context.getPackageName() + ".fileProvider";
            Uri apkUri = FileProvider.getUriForFile(context, authority, apkfile);
            LogUtils.w("----------------------2-------------------");
            //添加这一句表示对目标应用临时授权该Uri所代表的文件
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            LogUtils.w("----------------------3-------------------");
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
            LogUtils.w(">= 7.0以上手机 -手机---开始安装");
        } else {
            LogUtils.w("Build.VERSION.SDK_INT <= 24 开始安装");
            intent.setDataAndType(Uri.fromFile(apkfile), "application/vnd.android.package-archive");
        }

        context.startActivity(intent);
    }

}
